package com.phkj.qdh.ui.fragment.failover

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.cybertech.pdk.utils.GsonUtils
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentFailoverThingSelectBinding
import com.phkj.qdh.ui.adapter.FailoverThingsAdapter
import com.phkj.qdh.ui.fragment.myfailover.MyFailoverBaseDetailFragment
import com.phkj.qdh.ui.fragment.myfailover.MyFailoverLawDetailFragment
import com.phkj.qdh.ui.fragment.myfailover.MyFailoverTeamDetailFragment
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest
import java.util.HashMap

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 容错激励容错事件
 */
class FailoverThingSelectFragment : Fragment() {
    private var param1: Int? = null
    private var param2: Int? = null
    private val pageInfo = PageInfo()
    private val failoverThingsAdapter by lazy { FailoverThingsAdapter() }
    private lateinit var vm: FailoverVM
    private var _binding: FragmentFailoverThingSelectBinding? = null
    private val binding get() = _binding!!
    private lateinit var helper1: QuickAdapterHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getInt(ARG_PARAM1)
            param2 = it.getInt(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentFailoverThingSelectBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getFailoverVMProvider())[FailoverVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            rvFailoverThings.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(
                            requireContext(), R.color.transparent
                        ), 12
                    )
                )
            }
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack(
                    "things", FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
            srlFailoverThings.setOnRefreshListener {
                refresh()
            }
            btn.setOnClickListener {
                val data = failoverThingsAdapter.items.filter { it.isSelected }
                if (data.isNullOrEmpty()) {
                    ToastUtils.show("请选择折抵事项")
                    return@setOnClickListener
                } else {
                    parentFragmentManager.setFragmentResult(
                        "key",
                        bundleOf("data" to data)
                    )
                    parentFragmentManager.popBackStack()
                }
            }
        }


        helper1 = QuickAdapterHelper.Builder(failoverThingsAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    getData()
                }

                override fun onLoad() {
                    pageInfo.nextPage()
                    getData()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlFailoverThings.isRefreshing
                }
            }).build()
        binding.rvFailoverThings.adapter = failoverThingsAdapter
        failoverThingsAdapter.addOnItemChildClickListener(R.id.cb) { adapter, _, pos ->
            adapter.getItem(pos)!!.isSelected = !adapter.getItem(pos)!!.isSelected
            adapter.notifyItemChanged(pos)
        }

        failoverThingsAdapter.addOnItemChildClickListener(R.id.ll) { adapter, _, pos ->
            adapter.getItem(pos)!!.isSelected = !adapter.getItem(pos)!!.isSelected
            adapter.notifyItemChanged(pos)
        }


        failoverThingsAdapter.addOnItemChildClickListener(R.id.tv_Detail) { adapter, _, pos ->
            val data = adapter.getItem(pos)
            when (data?.eventType) {
                0 -> {
                    parentFragmentManager.commit {
                        addToBackStack("detail")
                        add(id, MyFailoverTeamDetailFragment.newInstance(data.id, ""))
                        setReorderingAllowed(true)
                    }
                }
                1->{//基础巡查
                    parentFragmentManager.commit {
                        addToBackStack("detail")
                        add(id, MyFailoverBaseDetailFragment.newInstance(data!!.id, ""))
                        setReorderingAllowed(true)
                    }
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.failoverReduceThingList.collectLatest {
                if (pageInfo.isFirstPage) {
                    failoverThingsAdapter.submitList(it)
                } else {
                    failoverThingsAdapter.addAll(it)
                }
                binding.srlFailoverThings.isRefreshing = false
                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    helper1.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    helper1.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.state.collectLatest {
                binding.srlFailoverThings.isRefreshing = false
            }
        }
        getData()
    }

    private fun getData() {
        val map = HashMap<String, Any?>()
        map["eventType"] = param1
        map["inspectTypeId"] = param2
        map["page"] = pageInfo.page
        map["size"] = PAGE_SIZE
        vm.getFailoverReduceThings(map)
    }

    private fun refresh() {
        pageInfo.reset()
        helper1.trailingLoadState = LoadState.None
        getData()
    }


    companion object {
        /**
         */
        @JvmStatic
        fun newInstance(param1: Int, param2: Int) = FailoverThingSelectFragment().apply {
            arguments = Bundle().apply {
                putInt(ARG_PARAM1, param1)
                putInt(ARG_PARAM2, param2)
            }
        }
    }
}